﻿/**
* ArrayExt.js
* 
* @author Demis Bellot
* @version 1.0
* 
* Copyright 2009, Demis Bellot
* http://code.google.com/p/ajaxstack/
*/

function ArrayExt() { }
var A = ArrayExt;
A.convertAll = function(array, convertFn)
{
	var to = [];
	for (var i = 0, len = array.length; i < len; i++)
		to[i] = convertFn(array[i]);
	return to;
}
A.contains = A.containsValue = function(array, item)
{
	for (var i = 0, len = array.length; i < len; i++) 
		if (array[i] == item) return true;

	return false;
}
A.count = function(array) 
{
    return array.length;
}
A.any = function(array, mapFn)
{
	for (var i = 0, len = array.length; i < len; i++) 
		if (mapFn(array[i])) return true;

	return false;
}
A.all = function(array, mapFn)
{
	for (var i = 0, len = array.length; i < len; i++)
		if (!mapFn(array[i])) return false;

	return true;
}
A.remove = function(array, from, to)
{
	var rest = array.slice((to || from) + 1 || array.length);
	array.length = from < 0 ? array.length + from : from;
	return array.push.apply(array, rest);
}
A.removeItem = function(array, item) {
    var pos = array.indexOf(item);
    if (pos != -1) array.splice(pos, 1);
    return array;
}
A.join = function(array, on)
{
	var s = "";
	on = on || ",";
	for (var i = 0, len = array.length; i < len; i++)
	{
		if (s) s += on;
		s += array[i];
	}
	return s;
}
A.isEmpty = function(array)
{
	return !array || array.length == 0;
}
A.each = function(array, fn)
{
	if (!array) return;
	for (var i = 0, len = array.length; i < len; i++)
		fn(array[i]);
}
A.merge = function(a1, a2)
{
	A.each(a2, function(item) { a1.push(item); });
	return a1;
}
A.cat = function()
{
	var all = [];
	for (var i = 0, len = arguments.length; i < arguments.length; i++)
	{
		A.merge(all, arguments[i]);
	}
	return all;
}
A.clone = function(array)
{
	return array.slice();
}
A.sort = function(array, sortFn) {
    array.sort(sortFn);
    return array;
}
A.areEqual = function(array, other) {
    if (!(is.Array(array) && is.Array(other))) return false;
    if (array.length != other.length) return false;

    for (var i = 0; i < array.length; i++) {
        if (!A.containsValue(other, array[i])) return false;
    }
    return true;
}
A.take = function(array, count) {
    var take = array.length < count ? array.length : count;
    var to = array.slice(0, take);
    return to;
}
A.skip = function(array, count) {
    var skip = array.length < count ? array.length : count;
    var to = array.slice(skip);
    return to;
}
A.prepend = function(array, item) {
    array.unshift(item);
}
A.insert = function(array, index, item) {
    var removedItems = array.splice(index, 0, item);
    return array;
}
A.where = function(array, predicateFn) {
    var to = [];    
    for (var i = 0, len = array.length; i < len; i++)
        if (predicateFn(array[i], i)) to.push(array[i]);
    return to;
}
